package cn.com.dragonsoftbravo.utils.web;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;


/***
 * *
* Sony PSS Project Source Code
* @copyright Promoters Sell-thru System, ISSG, Sony China
*
* @author Evan
* @date 2013-11-4
**
 */
public final  class CookieUtils {
	
	public static final String APP_LOGIN_USER = "app_login_user_cookie";
	
	public static final int SECOND = 1;
	public static final int MINUTES = 60 * SECOND;
	public static final int HOURS = 60 * MINUTES;
	public static final int DAYS = 24 * HOURS;
	
	/***
	 * 
	 * @param response
	 * @param name
	 * @param value
	 * @param expiry
	 * @author Evan
	 * @date 2013-11-4
	 */
	public static void addCookie(final HttpServletRequest request,final HttpServletResponse response,final String name,final String value,final int expiry){
		
		if(StringUtils.isBlank(name)){
			return;
		}
		//String key = PssEncryptionUtils.simpleMD5(name.toLowerCase());
		Cookie cookie = new Cookie(name,value); 
		cookie.setMaxAge(expiry);
		response.addCookie(cookie);
		
	}
	
	/***
	 * 
	 * @param request
	 * @param name
	 * @return
	 * @author Evan
	 * @date 2013-11-4
	 */
	public static String getCookieVal(final HttpServletRequest request,final String name){
		
		
		Cookie cookie = getCookie(request,name);
		String val = "";
		if(cookie != null){
			val = cookie.getValue();
		}
		
		return val;
	}
	
	/***
	 * 
	 * @param response
	 * @param name
	 * @author Evan
	 * @date 2013-11-4
	 */
	public static void removeCookie(final HttpServletRequest request,final HttpServletResponse response,final String name){
		
		addCookie(request,response, name,"",0);
	}
	
	/**
	 * 
	 * @param request
	 * @param name
	 * @return
	 * @author Evan
	 * @date 2013-11-4
	 */
	public static  Cookie getCookie(final HttpServletRequest request,final String name){
		
		//String key = PssEncryptionUtils.simpleMD5(name.toLowerCase());
		Cookie[] cookies = request.getCookies(); 
		if(ArrayUtils.isNotEmpty(cookies)){
			
			for(Cookie cookie : cookies){
				
				if(cookie.getName().equals(name)){
					
					return cookie;
				}
			}
		}
		return null;
	}
}
